package org.setamv.springcloud.hystrix.raw.command.strategy;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;

/**
 * 通过设置线程池的大小，使得超出线程池并发数的请求回退
 */
public class ThreadPoolStrategyCommandTest {

    public static void main(String[] args) throws Exception {
        // 设置Hystrix并发线程池的大小。当线程池满后，Hystrix对并发的更多请求会执行回退操作
        ConfigurationManager.getConfigInstance().setProperty("hystrix.strategy.default.coreSize", 3);

        // 下面使用command.queue方法使得多个命令异步执行，此时，因为线程池的大小被设置为3，所以下面执行的5个命令中会有2个因为线程池满了从而执行回退。
        for (int i = 0; i < 5; i++) {
            ThreadPoolThresholdCommand command = new ThreadPoolThresholdCommand(i);
            command.queue();
        }
        Thread.sleep(5000);
    }

    public static class ThreadPoolThresholdCommand extends HystrixCommand<String> {
        private int index;
        public ThreadPoolThresholdCommand(int index) {
            super(HystrixCommandGroupKey.Factory.asKey("testGroup"), 1000);
            this.index = index;
        }

        @Override
        protected String run() throws Exception {
            System.out.println("run " + index);
            return "run " + index;
        }

        @Override
        protected String getFallback() {
            System.out.println("fallback " + index);
            return "fallback " + index;
        }
    }
}
